package by.dvrudenko.avtobaza.services.impl;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.inject.Inject;

import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import by.dvrudenko.avtobaza.dataaccess.UserDao;
import by.dvrudenko.avtobaza.datamodel.User;
import by.dvrudenko.avtobaza.datamodel.User_;
import by.dvrudenko.avtobaza.datamodel.enums.UserRole;
import by.dvrudenko.avtobaza.services.UserService;

@Service
public class UserServiceImpl implements UserService{
	private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
	
	@Inject
	private UserDao dao;
	
	@PostConstruct
	private void init() {
		LOGGER.info("Instance of UserService is created. Class is: {}",
				getClass().getName());
	}
	
	@Override
	public User get(Long id) {
		User entity = dao.getById(id);
		return entity;
	}

	@Override
	public void saveOrUpdate(User user) {
		if (user.getId() == null) {
			LOGGER.debug("Save new: {user}", user);
			dao.insert(user);
		} else {
			LOGGER.debug("Update: {user}", user);
			dao.update(user);
		}
	}

	@Override
	public void delete(User user) {
		LOGGER.debug("Remove: {user}", user);
		dao.delete(user.getId());

	}

	@Override
	public void deleteAll() {
		LOGGER.debug("Remove all user");
		dao.deleteAll();
	}
    
    @Override
    public List<User> getAllUser() {
        return dao.getAllUser();
    }

	@Override
	public List<User> getAllUserByName(String name) {
        return dao.getAllUserByName(name);
	}

	@Override
	public List<User> getAllUSersByRole(UserRole userRole) {
		return dao.getAllByFieldRestriction(User_.role, userRole);
	}

	@Override // дописать валидацию
	public User getAccountByEmail(String email) {
		List<User> listUser = dao.getAllByFieldRestriction(User_.email, email);		
		return listUser.get(0); 
	}

	@Override
	public User getAccountByLogin(String login) {
		List<User> listUser = dao.getAllByFieldRestriction(User_.login, login);
		if (listUser.size()==0){
			return null;
		}
		return listUser.get(0); 
	}

	@Override
	public UserRole getRole(Long userId) {
		return dao.getById(userId).getRole();
	}

	
}
